package com.yeyaomai.dksns.flowis.servlet;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisStatDetailDTO;
import com.yeyaomai.dksns.flowis.service.FlowisQueryService;
import com.yeyaomai.dksns.flowis.service.result.KeyWordGain;
import com.yeyaomai.dksns.flowis.util.CollectionNames;

/**
 * 原始数据处理类
 * 
 * @author xiaqin
 * @date 2012.05.23
 */
@Controller
public class BaseController {

	@Autowired
	FlowisQueryService flowisQueryService;

	@RequestMapping("/getData")
	public void getData(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String data = request.getParameter("data");
		JSONObject object = JSONObject.fromObject(data);
		String refer = object.getString("refer");
		FlowisStatDetailDTO flow = new FlowisStatDetailDTO();
		flow.setReferer(refer);
		flow.setPageName(object.getString("page"));
		//flow.setCookieId(object.getString("cookieID"));
		flow.setAccess_url(object.getString("path"));
		flow.setOs(object.getString("os"));
		flow.setDomain(object.getString("domain"));
		flow.setBrowser(object.getString("browser"));
		flow.setLanguage(object.getString("lg"));
		flow.setScreen_resolution(object.getString("screenres"));
		//flow.setFirstVisit(Boolean.valueOf(object.getString("firVisit")));
		SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		flow.setAccess_date(date.format(Long.valueOf(object.getString("time"))));
		String keyword = "null";
		String engineName = "null";
		Integer req_source = 0;
		if (refer != "") {
			String engine = KeyWordGain.getDomain(refer);
			if (!engine.equals("null")) {
				engineName = engine;
				keyword = KeyWordGain.getKeyword(refer);
				req_source = CollectionNames.ENGIETYPE;
			}
			if (refer.indexOf("duankou") != -1) {
				req_source = CollectionNames.OUTTYPE;
			} else {
				req_source = CollectionNames.INTYPE;
			}
		} else {
			req_source = CollectionNames.DIRECTTYPE;
		}

		// String plugins = object.getString("plugins");//暂时未用
		// String flash = object.getString("flash");
		String ip = request.getRemoteAddr();
		flow.setIp(ip);
		flow.setSearch_engine(engineName);
		flow.setKey_word(keyword);
		flow.setReq_source(req_source);
		// getValueBuIp(flow, ip);
		
		Cookie cookies[] = request.getCookies();
		Cookie c = null;
		boolean isfirst=true;
		for(int i=0;i<cookies.length;i++)
		{
			c = cookies[i];
			if(c.getName().equals("duankouId"))
			{
				isfirst = false;
				flow.setCookieId(c.getValue());
			}
			if(c.getName().equals("visitCount"))
			{
				isfirst = false;
				int visitCount = Integer.valueOf(c.getValue())+1;
				c.setValue(String.valueOf(visitCount));
				c.setMaxAge(60*60*24*365);
				response.addCookie(c);
				flow.setVisitCount(visitCount);
			}
			
		}
		if(isfirst)
		{
			String id = UUID.randomUUID().toString();
			Cookie cookie = new Cookie("duankouId",id);
			cookie.setMaxAge(60*60*24*365);
			Cookie visitCount = new Cookie("visitCount", "1");
			 visitCount.setMaxAge(60*60*24*365);
			//cookie.setPath("/1");
			flow.setVisitCount(1);
			flow.setCookieId(id);
			response.addCookie(cookie);
			response.addCookie(visitCount);
		}
		flowisQueryService.insert(flow);
	}

	public static void getValueBuIp(FlowisStatDetailDTO flow, String ip)
			throws Exception {

		URL url = new URL("http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				url.openStream(), "GBK"));
		String getvalue = reader.readLine();
		String json = getvalue.substring(34, getvalue.length() - 3);
		JSONObject object = JSONObject.fromObject(json);
		String addr = object.getString("addr");
		String pro = object.getString("pro");
		String city = object.getString("city");
		flow.setAccess_country(null);
		flow.setInternet_provider(null);
		if (pro.equals("")) {
			flow.setAccess_country(object.getString("addr"));
		} else {
			String addrs[] = addr.split(" ");
			flow.setInternet_provider(addrs[1]);
		}
		flow.setAccess_province(pro);
		flow.setAccess_city(city);
		reader.close();

	}
}
